import { rspc } from '@fill/client';
import { useContext, useEffect } from 'react';
import JSONBig from 'json-bigint';
import AppRouter from './AppRouter';
import { FillContext } from './Fill';
import { Signin } from './Signin';
import { Splash } from './Splash';

function App() {
  const { login, setConfig, config } = useContext(FillContext);

  const { data, isLoading } = rspc.useQuery(['configs.all', { arg: null }]);

  useEffect(() => {
    const config: {
      [key: string]: any
    } = {};
    data?.forEach((item) => {
      console.log(item.value);
      try {
        const value = JSONBig.parse(item.value);
        config[item.key] = value;
      }
      catch (error) {
        config[item.key] = item.value;
      }
    });

    setConfig(config);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  function disableMenu() {
    // if (window.location.hostname !== 'tauri.localhost') {
    //   return
    // }

    document.addEventListener('contextmenu', (e) => {
      e.preventDefault();
      return false;
    }, { capture: true });

    document.addEventListener('selectstart', (e) => {
      e.preventDefault();
      return false;
    }, { capture: true });

    document.addEventListener('keydown', (e) => {
      e = e || window.event;
      console.log(e);
      if (e.key === 'F5' || e.code === 'F5' || e.keyCode === 116) {
        e.preventDefault();
        console.log('disable');
      }

      if (e.ctrlKey && (e.key === 'r' || e.keyCode === 82))
        e.preventDefault();
    });
  }

  import.meta.env.MODE !== 'development' && disableMenu();

  if (isLoading && !Object.keys(config).length)
    return <Splash />;

  if (!login) {
    return (
      <Signin />
    );
  }

  return (
    <AppRouter />
  );
}

export default App;
